package com.ticket.controller.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ticket.entity.TicketOrder;
import com.ticket.service.ITicketOrderService;
import com.ticket.utils.Result;
import com.ticket.utils.UserContext;
import com.ticket.vo.CreateOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/tickets")
public class TicketOrderController {

    @Autowired
    private ITicketOrderService ticketOrderService;

    @PostMapping("/order")
    public Result<Long> createOrder(@Valid @RequestBody CreateOrderVO orderVO) {
        try {
            Long userId = UserContext.getCurrentUserId();
            Long orderId = ticketOrderService.createOrder(userId, orderVO);
            return Result.success(orderId);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/pay/{orderId}")
    public Result<Boolean> payOrder(@PathVariable Long orderId) {
        try {
            Long userId = UserContext.getCurrentUserId();
            boolean success = ticketOrderService.payOrder(userId, orderId);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @PostMapping("/cancel/{orderId}")
    public Result<Boolean> cancelOrder(@PathVariable Long orderId) {
        try {
            Long userId = UserContext.getCurrentUserId();
            boolean success = ticketOrderService.cancelOrder(userId, orderId);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/orders")
    public Result<Page<TicketOrder>> getUserOrders(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(value = "status", required = false) String status) {
        Long userId = UserContext.getCurrentUserId();
        Page<TicketOrder> orders = ticketOrderService.getUserOrders(userId, page, size, status);
        return Result.success(orders);
    }

    @PostMapping("/refund/{orderId}")
    public Result<Boolean> refundOrder(@PathVariable Long orderId) {
        try {
            Long userId = UserContext.getCurrentUserId();
            boolean success = ticketOrderService.refundOrder(userId, orderId);
            return Result.success(success);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
